package com.unei.httpclient;

import org.apache.http.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;

import java.io.IOException;

/**
 * Created by sunlei on 2015/4/16.
 */
public class KeepAliveSample {
    public static void main(String[] args) throws IOException {

        ConnectionKeepAliveStrategy connectionKeepAliveStrategy=new ConnectionKeepAliveStrategy() {
            @Override
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
//                HeaderElementIterator it=new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
//                while(it.hasNext()){
//                    HeaderElement he=it.nextElement();
//                    String param=he.getName();
//                    String value=he.getValue();
//                    if(value!=null&&param.equalsIgnoreCase("timeout")){
//                        return Long.parseLong(value)*1000;
//                    }
//                }

                HttpHost httpHost=(HttpHost)context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
                System.out.println("---hostname:"+httpHost.getHostName());
                if("www.csdn.net".equalsIgnoreCase(httpHost.getHostName())){
                    return 5*1000;
                }else{
                    return 20*1000;
                }
            }
        };

        HttpClientConnectionManager httpClientConnectionManager=new BasicHttpClientConnectionManager();

        new IdleConnectionManager(httpClientConnectionManager).start();

        CloseableHttpClient httpClient= HttpClients.custom().setConnectionManager(httpClientConnectionManager)
                .setKeepAliveStrategy(connectionKeepAliveStrategy)
                        .build();
        HttpGet httpGet=new HttpGet("http://localhost:8080/unei-web/content/getContentById?id=1");
        CloseableHttpResponse response=httpClient.execute(httpGet);
        Header[] headers=response.getAllHeaders();
        for(Header header:headers){
            System.out.println(header.toString());
        }
        response.close();

        System.out.println("try second time........................");
        response=httpClient.execute(httpGet);
        headers=response.getAllHeaders();
        for(Header header:headers){
            System.out.println(header.toString());
        }

        response.close();
    }
}
